/**
* apisvr 主逻辑
*/

#ifndef __APISVR_CTRL_H__
#define __APISVR_CTRL_H__

#include "apidef.h"
#include "CTSizeString.h"

#include "commerrno.h"

#define CAPIEpollObject CTEpollObject<CAPICtrl>

namespace __gnu_cxx
{
    /*
    typedef CTSizeString<USER_TOKEN_LEN> SZ_USER_TOKEN;
    template<> struct hash<SZ_USER_TOKEN>
    { 
        size_t operator()(const SZ_USER_TOKEN& s) const
        {
            return __stl_hash_string(s.Get());
        }
    };
    */
}

class CAPICtrl
{
public:
    CAPICtrl();
	~CAPICtrl();

    static CAPICtrl * m_pstApiCtrl;

    int Init();
    int Run();
    int Exit();

    static void sigusr1_handle(int iSigVal);
    static void sigusr2_handle(int iSigVal);

    void OnEnpShmQueueEvent(CAPIEpollObject* pstObject, SOCKET iSocket, int iEvent);
    void OnTApiShmQueueEvent(CAPIEpollObject* pstObject, SOCKET iSocket, int iEvent);

    void DoNotResetShm()
    {
        m_bResetShm = false;
    }

    /**
    * 向TApi mpsvr发送请求
    */
    int RequestToTApi(const char* pszBuf, int iBufLen);

    /**
    * 向客户端返回简单的错误响应: CTMsgHead + CResult
    */
    int AnswerToClient(CEnpNetHead& stHead, CTCodeStream& s);
	int AnswerToClient(CEnpNetHead& stHead, CTMsgHead& stMsgHead, CResult& stRet);
    int AnswerToClient(CEnpNetHead& stHead, const char* sAnsMsg, int MsgLen);

protected:
    void DumpStatInfo();

    /**
    * 处理来自客户端的消息
    */
    void HandleEnpMsg();

    /**
    * 处理来自apisvr的消息
    */
    void HandleTApiMsg();

public:
    unsigned int		m_uiNow;    ///< 当前时间

    CTBuffer			    m_stEncodeBuf;  ///< 编码缓冲区
    CTBuffer			    m_stDecodeBuf;  ///< 解码缓冲区

protected:
    static bool s_bReloadConfig;
    static bool s_bExit;
    bool                    m_bResetShm; //是否重载内存中的数据

    CTEpoll				    m_stEpoll;
    CTShmQueue<CAPICtrl>     m_stEnpShmQueue;
    CTShmQueue<CAPICtrl>     m_stTApiShmQueue;
    CTShm                   m_stMgrShm;

    CTStat				    m_stStat;

public:

};



#endif //__APISVR_CTRL_H__
